package cn.chiship.bs.api.biz.service.impl;

import cn.chiship.bs.api.biz.entity.MemberUser;
import cn.chiship.bs.api.biz.entity.MemberUserExample;
import cn.chiship.bs.api.biz.mapper.MemberUserMapper;
import cn.chiship.bs.api.biz.pojo.vo.CacheUserVO;
import cn.chiship.bs.api.biz.service.MemberUserService;
import cn.chiship.bs.api.biz.service.UserCacheService;
import cn.chiship.bs.api.core.util.JwtUtil;
import cn.chiship.sdk.core.base.BaseResult;
import cn.chiship.sdk.core.enums.UserTypeEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class MemberUserServiceImpl extends BaseServiceImpl<MemberUser, MemberUserExample> implements MemberUserService {
    @Resource
    MemberUserMapper memberUserMapper;
    @Resource
    UserCacheService userCacheService;

    @Override
    public BaseResult appletLogin(String openId, String ip) {
        /**
         * 根据手机号查找用户
         */
        MemberUserExample memberUserExample = new MemberUserExample();
        memberUserExample.createCriteria().andWeixin1OpenIdEqualTo(openId);
        List<MemberUser> memberUsers = memberUserMapper.selectByExample(memberUserExample);
        MemberUser memberUser = null;
        if (memberUsers.isEmpty()) {
            /**
             * 不存在则注册
             */
            MemberUser user = new MemberUser();
            user.setWeixin1OpenId(openId);
            super.insertSelective(user);

            memberUser = user;
        } else {
            memberUser = memberUsers.get(0);
        }

        memberUser.setLastLoginIp(ip);
        memberUser.setLastLoginTime(System.currentTimeMillis());
        super.updateByPrimaryKeySelective(memberUser);
        CacheUserVO userVO = new CacheUserVO();
        userVO.setUserType(UserTypeEnum.MEMBER.getType());
        userVO.setMobile(memberUser.getMobile());
        userVO.setUsername(memberUser.getUserName());
        userVO.setId(memberUser.getId());
        userVO.setRealName(memberUser.getRealName());
        userVO.setAvatar(memberUser.getAvatar());
        userVO.setExtInfo(memberUser.getTags());
        String accessToken = JwtUtil.createToken(userVO);
        userCacheService.cacheUser(accessToken, userVO);
        return BaseResult.ok(accessToken);
    }
}
